﻿using System;

namespace Crm2011.Framework.Core
{
    /// <summary>
  /// </summary>
  /// <typeparam name="TEnum"></typeparam>
  public static class EnumHelper<TEnum> 
  {
    /// <summary>
    /// Check if a String can be converted to any item of the enumeration.
    /// The String can be the text representation of the enumitem name or 
    /// the enumitem value.
    /// </summary>
    /// <example>
    ///   EnumHelper&lt;ReturnCodePickListItems&gt;.IsDefined(enumString)
    /// </example>
    public static bool IsDefined(string itemString)
    {
      //http://msdn.microsoft.com/en-us/library/kxydatf9.aspx
      bool result;
      try
      {
        TEnum itemValue = (TEnum)Enum.Parse(typeof(TEnum), itemString, true);
        result = (Enum.IsDefined(typeof(TEnum), itemValue) | itemValue.ToString().Contains(","));
      }
      catch (ArgumentException)
      {
        result = false;
      }
      return result;
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="itemString"></param>
    /// <returns></returns>
    public static int GetValue(string itemString)
    {
      return Convert.ToInt32(GetEnumItem(itemString));
    }

    /// <summary>
    /// Gets the enum item.
    /// </summary>
    /// <param name="itemString">The item string.</param>
    /// <returns></returns>
    public static TEnum GetEnumItem(string itemString)
    {
      if (!IsDefined(itemString))
        throw new ArgumentException(string.Format("The string {0} is not an item of the {1} enumeration", itemString, typeof(TEnum)));

      return (TEnum)Enum.Parse(typeof(TEnum), itemString, true);
    }

    /// <summary>
    /// Gets the enum item.
    /// </summary>
    /// <param name="itemValue">The item value.</param>
    /// <returns></returns>
    public static TEnum GetEnumItem(int itemValue)
     {
       return (TEnum) Enum.ToObject(typeof (TEnum), itemValue);
     }

  }

}
